<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public $timestamps = false;
    
    protected $table = 'category';
    protected $primaryKey = 'cate_id';
    protected $guarded = [];
    
    public static function tree(){
        $categories = Category::orderBy('cate_order', 'asc')->get();
        return Category::getTree($categories, 'cate_name', 'cate_id', 'cate_parentid');
    }

    public static function getTree($data, $field_name, $field_id = 'id', $field_parentid = 'parentid', $parentid = 0) {
        $arr = [];
        foreach ($data as $key => $value) {
            if ($value->$field_parentid == $parentid) {
                $value['prefix_' . $field_name] = $value[$field_name];
                $arr[] = $value;
                foreach ($data as $k => $v) {
                    if ($v->$field_parentid == $value->$field_id) {
                        $v['prefix_' . $field_name] = '----' . $v[$field_name];
                        $arr[] = $v;
                    }
                }
            }
        }
        return $arr;
    }

}
